<template>
  <div class="data-table-container">
    <div class="page-header">
      <div class="header-content">
        <h2>数据表管理</h2>
        <!-- <p>系统数据表结构和数据管理</p> -->
      </div>
      <div class="header-actions">
        <el-button type="warning" @click="backupDatabase" >          
          <el-icon><WarnTriangleFilled /></el-icon>
          高级权限
        </el-button>
        <el-button type="primary" @click="backupDatabase" >
          <el-icon><Download /></el-icon>
          备份数据
        </el-button>
        <el-button type="primary" @click="backupDatabase" >
          <el-icon><Upload /></el-icon>
          恢复数据
        </el-button>
        <!-- <el-button type="primary" @click="createTable" >
          <el-icon><Plus /></el-icon>
          创建数据表
        </el-button> -->
      </div>
    </div>

     <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in dataTypes" :key="item.label">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-label">{{ item.label }}</div>
              <div class="stat-number">{{ item.value }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="content-wrapper">
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="表名">
            <el-input 
              v-model="filterForm.name" 
              placeholder="请输入表名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="表类型">
            <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
              <el-option label="业务表" value="business" />
              <el-option label="系统表" value="system" />
              <el-option label="日志表" value="log" />
              <el-option label="配置表" value="config" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-section">
        <el-table :data="tableData" v-loading="loading" stripe border>
          <el-table-column prop="name" label="表名"/>
          <el-table-column prop="comment" label="表注释" width="300" />
          <el-table-column prop="type" label="表类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">
                {{ getTypeText(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="rowCount" label="记录数" width="120" />
          <el-table-column prop="size" label="占用空间" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <!-- <el-table-column prop="updateTime" label="更新时间" width="160" /> -->
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
               <el-tooltip content="查看详情" placement="top" show-after="1000">
                <el-button type="primary" link @click="handleSee(row)">
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>

               <el-tooltip content="编辑" placement="top" show-after="1000">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
               <el-tooltip content="清理" placement="top" show-after="1000">
                <el-button type="primary" link @click="exportTable(row)">
                  <el-icon><EditPen /></el-icon>
                </el-button>
              </el-tooltip>
              
               <el-tooltip content="删除" placement="top" show-after="1000">
                <el-button type="danger" link @click="deleteTable(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
     <!-- 弹框 -->
    <el-dialog
      :title="viewDetail.title"
      v-model="viewDetail.open"
      width="800px"
      append-to-body
    >
      <Form
        v-if="viewDetail.open"
        :columns="viewDetail.columns"
        :data="viewDetail.form"
        :rules="viewDetail.rules"
        :inline="false"
        :disabled="viewDetail.disabled"
        :buttons="viewDetail.buttons"
        :key="viewDetail.disabled"
        height="350px"
        @submit="viewDetail.submit"
        @cancel="viewDetail.cancel"
      >
      </Form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, WarnTriangleFilled, Upload, Edit, View, Delete, EditPen } from '@element-plus/icons-vue'

const dataTypes = [
  { label: "数据表总数", value: "12345" },
  { label: "记录总数", value: "9564" },
  { label: "数据大小", value: "1.2GB" },
  { label: "最后备份", value: "24小时前" },
];

// 响应式数据
const loading = ref(false)
const tableData = ref([])

// 筛选表单
const filterForm = reactive({
  name: '',
  type: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 模拟数据
const mockData = [
  {
    id: 1,
    name: 'users',
    comment: '用户信息表',
    type: 'business',
    rowCount: 1250,
    size: '2.5 MB',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-20 14:30:00'
  },
  {
    id: 2,
    name: 'tactical_plans',
    comment: '战术方案表',
    type: 'business',
    rowCount: 85,
    size: '1.2 MB',
    createTime: '2024-01-05 09:30:00',
    updateTime: '2024-01-19 16:45:00'
  },
  {
    id: 3,
    name: 'system_logs',
    comment: '系统日志表',
    type: 'log',
    rowCount: 50000,
    size: '15.8 MB',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-20 14:35:00'
  },
  {
    id: 4,
    name: 'system_config',
    comment: '系统配置表',
    type: 'config',
    rowCount: 45,
    size: '64 KB',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-15 11:20:00'
  },
  {
    id: 5,
    name: 'vulnerabilities',
    comment: '漏洞信息表',
    type: 'business',
    rowCount: 320,
    size: '890 KB',
    createTime: '2024-01-10 14:20:00',
    updateTime: '2024-01-20 13:15:00'
  }
]

// 生命周期
onMounted(() => {
  fetchData()
})

// 方法
const fetchData = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const resetFilter = () => {
  filterForm.name = ''
  filterForm.type = ''
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchData()
}

const backupDatabase = () => {
  ElMessage.success('正在备份数据库...')
}

const exportTable = (row) => {
  ElMessage.success(`正在导出表: ${row.name}`)
}

const deleteTable = (row) => {
  ElMessageBox.confirm(`确认删除表"${row.name}"吗？此操作不可恢复。`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  })
}

// 工具函数
const getTypeTagType = (type) => {
  const tagMap = {
    business: 'primary',
    system: 'success',
    log: 'warning',
    config: 'info'
  }
  return tagMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    business: '业务表',
    system: '系统表',
    log: '日志表',
    config: '配置表'
  }
  return textMap[type] || '未知'
}

// 列字段
const columns = ref([
  {
    prop: "name",
    label: "表名",
    type: "input",
    width: "100%",
    formItemWidth: "100%",
  },
  {
    prop: "comment",
    label: "表注释",
    type: "input",
    width: "100%",
    formItemWidth: "100%",
  },
  {
    prop: "type",
    label: "表类型",
    type: "select",
    options: [
      { value: "发现", label: "发现" },
      { value: "凭据访问", label: "凭据访问" },
      { value: "初始访问", label: "初始访问" },
    ],
    width: "100%",
    formItemWidth: "100%",
  },
  {
    prop: "rowCount",
    label: "记录数",
    type: "input",
    width: "100%",
    formItemWidth: "100%",
  },
  {
    prop: "size",
    label: "占用空间",
    type: "input",
    width: "100%",
    formItemWidth: "100%"
  },
]);
const handleCreate = () => {
  viewDetail.value.title = "创建";
  viewDetail.value.disabled = false;
  viewDetail.value.open = true;
  viewDetail.value.form = {};
  viewDetail.value.buttons = [
    { type: "default", text: "取消", prop: "cancel" },
    { type: "primary", text: "提交", prop: "submit" },
  ];
};

const handleSee = (row) => {
  viewDetail.value.title = "查看";
  viewDetail.value.disabled = true;
  viewDetail.value.open = true;
  viewDetail.value.form = row;
  viewDetail.value.buttons = [
    { type: "default", text: "取消", prop: "cancel" },
  ];
};
const handleEdit = (row) => {
  viewDetail.value.title = "编辑";
  viewDetail.value.disabled = false;
  viewDetail.value.open = true;
  viewDetail.value.form = row;
  viewDetail.value.buttons = [
    { type: "default", text: "取消", prop: "cancel" },
    { type: "primary", text: "提交", prop: "submit" },
  ];
};
const viewDetail = ref({
  title: "",
  open: false,
  disabled: false,
  form: {
    id: "",
    timeAppointment0: null,
    timeAppointment1: null,
    street: null,
    address: null,
    cusAddress: null,
    remark: null,
  },
  originData: {},
  columns: [
    {
      title: "",
      cols: columns.value,
    },
  ],
  rules: [],
  submit: (val) => {
    if (val.id) {
      ElMessage.success("编辑漏洞成功");
    } else {
      tableData.value.push(val);
      ElMessage.success("添加漏洞成功");
    }

    viewDetail.value.open = false;
  },
  cancel: () => {
    viewDetail.value.open = false;
  },
  buttons: [
    { type: "primary", text: "保存", prop: "submit" },
    { type: "default", text: "取消", prop: "cancel" },
  ],
});
</script>

<style lang="scss" scoped>
.data-table-container {
  background-color: var(--bg-color);
}

  .header-content {
    h2 {
      margin: 0 0 8px 0;
      color: var(--text-color);
      font-size: 24px;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: var(--text-color-secondary);
      font-size: 14px;
    }
  }






.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 